package gant

import gant.tools.ClassUtils
import org.codehaus.gant.GantBinding
import org.slf4j.LoggerFactory

/**
 * Created by IntelliJ IDEA.
 * User: tbarker
 * Date: 4/4/12
 * Time: 1:53 PM
 */
class GantActivator {

    Script script
    Binding binding
    Gant gant

    def static activateGant(Script script) {
        new GantActivator(script: script).with {
            addBindingToScript()
            addExecuteTargets()
            overrideIncludeTargets()
            setUpSlf4j()
            addLogging()
        }
    }

    def setUpSlf4j() {
        try {
            ClassUtils.forName("org.slf4j.impl.StaticLoggerBinder")
            //do nothing slf4j is already set up
        } catch (ClassNotFoundException ex) {
            def factory = new AntLoggingFactory()

            LoggerFactory.metaClass.static.getLogger = {String loggerName ->
                factory.getLogger(loggerName)
            }
        }
    }

    def addLogging() {
        getBinding().setVariable("log", LoggerFactory.getLogger(AntLoggingFactory.GANT))
    }

    def overrideIncludeTargets() {
        getBinding().forcedSettingOfVariable ( 'includeTargets' , new IncludeTargetsWithStringAsClassName ( this.binding ) )
    }

    Binding getBinding() {
        if(binding) {
            return binding
        }

        binding = new GantBinding(script.binding)
    }

    Gant getGant() {
        if(gant) {
            return gant
        }

        gant = new Gant(getBinding())
    }

    void addBindingToScript() {
        def bindingToUse = getBinding()
        if (!AntBindingFactory.bindingFactoryExists()) {
            AntBindingFactory.createInstance(bindingToUse)
        }
        script.binding = bindingToUse
    }

    void addExecuteTargets() {
        getBinding().executeTargets = {List<String> targets ->
            getScript().metaClass.run = {->
                //do nothing, already running
            }

            getGant().executeTargets()
        }
    }

}
